﻿
#include "../iocp/IOCP/fileio.h"
#include "iocpsrv.h"
#include <process.h>

//INT ExecNetServerCmd(CONST CString& strArgument)
//{
//    InitLog(L"netserver");
//
//    if (!utils::system::add_firewall_ruler_ex(utils::process::get_exe_path(), L"start_in", true) ||
//        !utils::system::add_firewall_ruler_ex(utils::process::get_exe_path(), L"start_out", false))
//    {
//        ERR_LOG(L"add_firewall_ruler_ex failed");
//        //utils::system::add_firewall_ruler(utils::process::get_exe_path(), L"start");
//    }
//
//    //::Sleep(30 * 1000);
//    if (L"start" == strArgument)
//    {
//        HANDLE hEvent = CreateEvent(nullptr, TRUE, FALSE, IOCP_EVENT_NAME);
//
//        if (nullptr == hEvent)
//        {
//            return 1;
//        }
//
//        CIocpSrv IocpSrv;
//        IocpSrv.InitEnv();
//
//        WaitForSingleObject(hEvent, -1);
//        IocpSrv.UninitEnv();
//        CloseHandle(hEvent);
//        return 0;
//    }
//    HANDLE hEvent = OpenEvent(EVENT_ALL_ACCESS, FALSE, IOCP_EVENT_NAME);
//    if (nullptr == hEvent)
//    {
//        return 1;
//    }
//
//    SetEvent(hEvent);
//    CloseHandle(hEvent);
//    return 0;
//}

CIocpSrv::CIocpSrv()
    : m_hIocp(nullptr)
      , m_bInit(FALSE)
{
}

CIocpSrv::~CIocpSrv()
{
    if (m_hIocp)
    {
        iobase_free(m_hIocp);
        m_hIocp = nullptr;
    }

    m_bInit = FALSE;
}

BOOL CIocpSrv::InitEnv()
{
    if (nullptr != m_hIocp)
    {
        return FALSE;
    }

    if (FALSE == m_bInit && FALSE == iocp_init_env())
    {
        return FALSE;
    }

    m_bInit = TRUE;
    m_hIocp = iobase_new();

    if (nullptr == m_hIocp)
    {
        return FALSE;
    }
    return TRUE;
}

void CIocpSrv::UninitEnv()
{
    if (m_hIocp)
    {
        iobase_loopexit(m_hIocp);
    }

    if (m_hIocp)
    {
        iobase_free(m_hIocp);
        m_hIocp = nullptr;
    }

    if (m_bInit)
    {
        iocp_uninit_env();
    }
    m_bInit = FALSE;
}

unsigned CIocpSrv::Dispatch()
{
    PHTTPSERVER pServer = http_listen(m_hIocp);

    //注册错误接收
    http_register_errorcall(pServer, CHttpHandles::ErrorHandle);
    // 在这里监听各种事件
    http_register_pathcall(pServer, "api/Login", CHttpHandles::Login);
    http_register_pathcall(pServer, "api/Logout", CHttpHandles::Logout);
    http_register_pathcall(pServer, "api/HeartBeat", CHttpHandles::HeartBeat);
    http_register_pathcall(pServer, "api/GetPermissions", CHttpHandles::GetPermissions);
    
    http_register_pathcall(pServer, "*", CHttpHandles::General);
    iobase_dispatch(m_hIocp); //消息循环

    // 准备退出了
    http_listen_close(pServer);

    return 0;
}
